<?php
/**
 * @desc
 * @author: jintao
 * @since: 2016/7/21
 */
class erpapi_shop_response_process_aftersalev2 {

    public function add($sdf) {
        switch($sdf['response_bill_type']) {
            case 'refund_apply' :
                $rs = $this->_dealRefundApply($sdf);
                break;
            case 'refund' :
                $rs = $this->_dealRefund($sdf);
                break;
            case 'return_product' :
                $rs = $this->_dealReturnProduct($sdf);
                break;
            case 'reship' :
                $rs = $this->_dealReship($sdf);
                break;
            default :
                $rs = array('rsp'=>'fail', 'msg'=>'没有单据类型');
        }
        return $rs;
    }

    private function _dealRefundApply($sdf) {
        if ($sdf['refund']) {
            return $this->_hadRefund($sdf);
        }
        $modelRefundApply = app::get('ome')->model('refund_apply');
        $oOperation_log = app::get('ome')->model('operation_log');//写日志
        if($sdf['refund_apply']) {
            $refundApply = $sdf['refund_apply'];
            $filter = array('apply_id' => $refundApply['apply_id']);
            switch($sdf['status']) {
                case '0':
                    $upData = $this->_refundApplySdfToData($sdf);
                    $memo = '(退款金额、原因或版本变化)退款申请单更新为未审核';
                    break;
                default :
                    $upData = array(
                        'status' => $sdf['status'],
                        'outer_lastmodify'=> $sdf['modified'],
                    );
                    if($sdf['refund_version_change']) {
                        $upData['memo']  = $sdf['reason'];
                        $upData['money'] = $sdf['refund_fee'];
                    } else {
                        $filter['memo'] = $sdf['reason'];
                        $filter['money'] = $sdf['refund_fee'];
                    }
                    $memo = '更新成功,状态：' . $sdf['status'];
                    break;
            }
            $rs = $modelRefundApply->update($upData, $filter);
            $idBn = array(
                'apply_id' => $refundApply['apply_id'],
                'refund_apply_bn' => $upData['refund_apply_bn']
            );
            $this->_dealTableAdditional($sdf['table_additional'], $idBn);
            if(!is_bool($rs)) {
                $oOperation_log->write_log('refund_apply@ome', $refundApply['apply_id'], $memo);
            }
            
            //更新订单支付状态、叫回发货单等
            kernel::single('ome_order_func')->update_order_pay_status($sdf['order']['order_id']);
            
        } else {
            $insertData = $this->_refundApplySdfToData($sdf);
            //创建退款单
            $is_update_order    = true;//是否更新订单付款状态
            $rs = kernel::single('ome_refund_apply')->createRefundApply($insertData, $is_update_order, $error_msg);
            if(!$rs) {
                return array('rsp'=>'fail', 'msg'=>'退款申请单生成失败');
            }
            
            $idBn = array(
                'apply_id' => $insertData['apply_id'],
                'refund_apply_bn' => $insertData['refund_apply_bn']
            );
            $this->_dealTableAdditional($sdf['table_additional'], $idBn);
            $memo = '创建退款申请单,状态：' . $sdf['status'].$sdf['memo'];
            $oOperation_log->write_log('refund_apply@ome',$insertData['apply_id'],$memo);
        }
        
        //识别是否天猫退款触发AG接口
        $noticeParams = array_merge($sdf, $idBn);
        $this->_noticeAg($noticeParams);

        return array('rsp'=>'succ', 'msg'=>$memo);
    }

    private function _refundApplySdfToData($sdf) {
        $data = array(
            'order_id'        => $sdf['order']['order_id'],
            'refund_apply_bn' => $sdf['refund_bn'],
            'pay_type'        => $sdf['pay_type'],
            'account'         => $sdf['account'],
            'bank'            => $sdf['bank'],
            'pay_account'     => $sdf['pay_account'],
            'money'           => $sdf['refund_fee'],
            'refunded'        => '0',
            'memo'            => $sdf['reason'],
            'create_time'     => $sdf['created'],
            'status'          => $sdf['status'],
            'shop_id'         => $sdf['shop_id'],
            'addon'           => serialize(array('refund_bn'=>$sdf['refund_bn'])),
            'source'          => 'matrix',
            'shop_type'       => $sdf['shop_type'],
            'outer_lastmodify'=> $sdf['modified'],
            'refund_refer'    => in_array($sdf['order']['ship_status'],array('1','3')) ? '1' : '0',
        );
        if($sdf['refund_item_list']) {
            $arrProduct = array();
            foreach($sdf['refund_item_list'] as $val) {
                $arrProduct[] = array(
                    'product_id'    => $val['product_id'],
                    'bn'            => $val['bn'],
                    'name'          => $val['title'] ? $val['title'] : $val['name'],
                    'num'           => $val['num'],
                    'price'         => $val['price'],
                    'oid'           => $val['oid'],
                    'refund_phase'  => $val['refund_phase'],
                    'refund_memo'   => $val['refund_memo'],
                    'modified'      => kernel::single('ome_func')->date2time($val['modified']),
                );
            }
            $data['product_data'] = serialize($arrProduct);
        }
        return $data;
    }

    private function _dealTableAdditional($tableAdditional, $idBn) {
        if(empty($tableAdditional) || empty($idBn)) {
            return false;
        }
        $model = app::get('ome')->model($tableAdditional['model']);
        $data = array_merge($tableAdditional['data'], $idBn);
        $model->db_save($data);
    }

    #退款单已经存在处理
    private function _hadRefund($sdf) {
        $modelRefundApply = app::get('ome')->model('refund_apply');
        $oOperation_log = app::get('ome')->model('operation_log');//写日志
        $msg = '退款单' . $sdf['refund']['refund_bn'] . '已经存在';
        if($sdf['refund_apply'] && $sdf['refund_apply']['status'] != '4') {
            $modelRefundApply->update(array('status' => '4'), array('apply_id' => $sdf['refund_apply']['apply_id']));
            $msg .= '  更新退款申请单为已退款';
            $oOperation_log->write_log('refund_apply@ome', $sdf['refund_apply']['apply_id'], '退款单已存在，自动更新为已退款');
        }
        return array('rsp'=>'succ', 'msg'=>$msg);
    }

    private function _dealRefund($sdf) {
        if ($sdf['refund']) {
            return $this->_hadRefund($sdf);
        }
        $data = $this->_refundsdfToData($sdf);
        $rs = app::get('ome')->model('refunds')->insert($data);
        if(!$rs) {
            return array('rsp'=>'fail', 'msg'=>'退款单创建失败');
        }
        $msg = '创建退款单';
        $refundApply = $sdf['refund_apply'];
        if ($refundApply) {
            $filter = array(
                'apply_id' => $refundApply['apply_id'],
            );
            $updateData = array('status' => '4','refunded' => $sdf['refund_fee']);
            app::get('ome')->model('refund_apply')->update($updateData,$filter);
            app::get('ome')->model('operation_log')->write_log('refund_apply@ome', $refundApply['apply_id'], '退款成功');
            $msg .= "&nbsp;&nbsp;更新退款申请单[{$refundApply['refund_apply_bn']}]为已退款";
            if ($refundApply['addon']) {
                $addon = unserialize($refundApply['addon']);
                $return_id = $addon['return_id'];
                if ($return_id) {
                    $pReturnModel = app::get('ome')->model('return_product');
                    $pReturnData = $pReturnModel->getList('refundmoney,return_bn', array('return_id' => $return_id), 0, 1);
                    $pReturn = $pReturnData[0];
                    $refundMoney = bcadd((float)$sdf['refund_fee'], (float)$pReturn['refundmoney'],3);
                    $pReturnModel->update(array('refundmoney'=>$refundMoney),array('return_id'=>$return_id));
                    $return_bn = $pReturn['return_bn'];
                    $msg .= "&nbsp;&nbsp;更新售后申请单[{$return_bn}]金额：".$refundMoney;

                    //如果是售后退货完成产生的退款完成更新，生成售后单
                    if($sdf['tmall_has_finished_return_product']){
                        kernel::single('sales_aftersale')->generate_aftersale($refundApply['apply_id'],'refund');
                    }
                }
            }
        }
        if($this->_updateOrderPayed($sdf['order']['order_id'],$sdf['refund_fee'])) {
            $msg .= '&nbsp;&nbsp;更新订单支付状态';
        }
        return array('rsp'=>'succ', 'msg'=>$msg);
    }

    private function _refundSdfToData($sdf) {
        $data = array(
            'refund_bn'     => $sdf['refund_bn'],
            'shop_id'       => $sdf['shop_id'],
            'order_id'      => $sdf['order']['order_id'],
            'currency'      => 'CNY',
            'money'         => $sdf['refund_fee'],
            'cur_money'     => $sdf['cur_money'] ? $sdf['cur_money'] : $sdf['refund_fee'],
            'pay_type'      => $sdf['pay_type'],
            'download_time' => time(),
            'status'        => 'succ',
            'memo'          => $sdf['reason'],
            'trade_no'      => $sdf['alipay_no'],
            'modifiey'      => $sdf['modified'],
            'payment'       => $sdf['payment'],
            't_ready'       => $sdf['t_ready'] ? $sdf['t_ready'] : $sdf['t_sent'],
            't_sent'        => $sdf['t_sent'] ? $sdf['t_sent'] : $sdf['t_ready'],
            't_received'    => $sdf['t_received']
        );
        return $data;
    }

    private function _updateOrderPayed($orderId, $money) {
        if (empty($orderId) || !$money) {
            return false;
        }
        $sql ="update sdb_ome_orders set payed=IF((CAST(payed AS char)-IFNULL(0,cost_payment)-".$money.")>=0,payed-IFNULL(0,cost_payment)-".$money.",0)  where order_id=".$orderId;
        kernel::database()->exec($sql);
        //更新订单支付状态
        if (kernel::single('ome_order_func')->update_order_pay_status($orderId)){
            $this->_checkAbnormal($orderId);
            return true;
        }else{
            return false;
        }
    }

    protected function _checkAbnormal($orderId){
        if (empty($orderId)) {
            return false;
        }
        $orderObj = app::get('ome')->model('orders');
        $orderData = $orderObj->getList('pay_status,ship_status', array('order_id'=>$orderId), 0, 1);
        $tgOrder = $orderData[0];
        #未发货、部分发货，暂停处理
        if($tgOrder['pay_status'] == '4' && ($tgOrder['ship_status'] == '0' || $tgOrder['ship_status']== '2')){
            $tmp = array();
            //如果是部分退款订单,添加部分退款异常并暂停订单
            $abnormalObj = app::get('ome')->model('abnormal');
            $abnormalTypeObj = app::get('ome')->model('abnormal_type');
            $abnormalTypeInfo = $abnormalTypeObj->getList('type_id,type_name', array('type_name'=>'订单未发货部分退款'), 0, 1);
            if($abnormalTypeInfo){
                $tmp['abnormal_type_id'] = $abnormalTypeInfo[0]['type_id'];
            }else{
                $add_arr['type_name'] = '订单未发货部分退款';
                $abnormalTypeObj->insert($add_arr);
                $tmp['abnormal_type_id'] = $add_arr['type_id'];
            }
            $abnormalInfo = $abnormalObj->getList('abnormal_id,abnormal_memo', array('order_id'=>$orderId), 0, 1);
            $memo = '';
            if($abnormalInfo){
                $tmp['abnormal_id'] = $abnormalInfo[0]['abnormal_id'];
                $oldmemo= unserialize($abnormalInfo[0]['abnormal_memo']);
                if ($oldmemo){
                    foreach($oldmemo as $k=>$v){
                        $memo[] = $v;
                    }
                }
            }
            $op_name = 'system';
            $newmemo =  '订单未发货部分退款，系统自动设置为异常并暂停。';
            $memo[] = array('op_name'=>$op_name, 'op_time'=>date('Y-m-d H:i',time()), 'op_content'=>$newmemo);
            $tmp['abnormal_memo'] = serialize($memo);
            $tmp['abnormal_type_name'] ='订单未发货部分退款';
            $tmp['is_done'] = 'false';
            $tmp['order_id'] = $orderId;
            if($tmp['abnormal_id']) {
                $abnormalObj->update($tmp, array('abnormal_id' => $tmp['abnormal_id']));
            } else {
                $abnormalObj->insert($tmp);
            }
            //如果已经有发货单的撤销相关发货单
            $orderObj->cancel_delivery($orderId);
            //订单暂停并设置为异常
            $orderObj->update(array('abnormal'=>'true','pause'=>'true'), array('order_id'=>$orderId));
        }
    }

    private function _dealReturnProduct($sdf) {
        $modelReturnProduct = app::get('ome')->model('return_product');
        if($sdf['return_product']) {
            $idBn = array(
                'return_id' => $sdf['return_product']['return_id'],
                'return_bn' => $sdf['return_product']['return_bn']
            );
            $this->_dealTableAdditional($sdf['table_additional'], $idBn);
            $this->_returnProductUpdateStatus($sdf);
            $msg = '更新成功';
        } else {
            $insertData = $this->_returnProductSdfToData($sdf);
            $returnProductItems = $insertData['return_product_items'];
            unset($insertData['return_product_items']);
            $rs = $modelReturnProduct->insert($insertData);
            if(!$rs) {
                return array('rsp'=>'fail', 'msg'=>'售后申请单新建失败');
            }
            $this->_insertReturnProductItems($returnProductItems, $insertData['return_id']);
            app::get('ome')->model('operation_log')->write_log('return@ome',$insertData['return_id'],'创建售后申请单');
            $msg = '创建售后申请单成功';
            $idBn = array(
                'return_id' => $insertData['return_id'],
                'return_bn' => $insertData['return_bn']
            );
            $this->_dealTableAdditional($sdf['table_additional'], $idBn);
            if (in_array($sdf['status'],array('3','5','6'))) {
                $this->_returnProductUpdateStatus($sdf);
            } elseif($sdf['status'] == '4') {
                return array('rsp'=>'fail', 'msg'=>'退货单未生成，不能完成');
            }
        }
        return array('rsp'=>'succ', 'msg' => $msg);
    }

    private function _returnProductSdfToData($sdf) {
        $opInfo = kernel::single('ome_func')->get_system();
        $data = array(
            'return_bn'  => $sdf['refund_bn'],
            'shop_id'    => $sdf['shop_id'],
            'member_id'  => $sdf['member_id'],
            'order_id'   => $sdf['order']['order_id'],
            'title'      => $sdf['order_bn'].'售后申请单',
            'content'    => $sdf['reason'],
            'comment'    => $sdf['desc'],
            'add_time'   => $sdf['created'],
            'status'     => '1',
            'op_id'      => $opInfo['op_id'],
            'refundmoney'=> $sdf['refund_fee'],
            'money'      => $sdf['refund_fee'],
            'shipping_type'=> $sdf['shipping_type'],
            'source'     => 'matrix',
            'shop_type'  => $sdf['shop_type'],
            'outer_lastmodify'=>$sdf['modified'],
            'delivery_id'=> $sdf['delivery_id'],
            'memo'      =>  $sdf['memo'],
        );
        $isFail = 'false';
        foreach($sdf['refund_item_list'] as $val) {
            $data['return_product_items'][] = array(
                'product_id' => $val['product_id'] ? $val['product_id'] : 0,
                'bn'         => $val['bn'],
                'name'       => $val['title'] ? $val['title']: $val['name'],
                'num'        => $val['num'],
                'price'      => $val['price'],
                'branch_id'   =>$sdf['branch_id'],
            );
            if(empty($val['product_id'])) {
                $isFail = 'true';
            }
        }
        $data['is_fail'] = $isFail;
        return $data;
    }

    private function _insertReturnProductItems($returnProductItems, $returnId) {
        if(empty($returnId) || empty($returnProductItems)) {
            return false;
        }
        foreach($returnProductItems as &$val) {
            $val['return_id'] = $returnId;
        }
        $modelItem = app::get('ome')->model('return_product_items');
        $sql = ome_func::get_insert_sql($modelItem, $returnProductItems);
        $rs = $modelItem->db->exec($sql);
        return $rs['rs'];
    }

    private function _returnProductUpdateStatus($sdf) {
        $operateLog = app::get('ome')->model('operation_log');
        $modelReturnProduct = app::get('ome')->model('return_product');
        $returnProduct = $sdf['return_product'];
        switch($sdf['status']) {
            case '1':
                $upData = $this->_returnProductSdfToData($sdf);
                $returnProductItems = $upData['return_product_items'];
                unset($upData['return_product_items']);
                $modelReturnProduct->update($upData, array('return_id'=>$returnProduct['return_id']));
                app::get('ome')->model('return_product_items')->delete(array('return_id'=>$returnProduct['return_id']));
                $this->_insertReturnProductItems($returnProductItems, $returnProduct['return_id']);
                $operateLog->write_log('return@ome', $returnProduct['return_id'], '退款原因、金额或版本变化，重置售后申请单');
                if($sdf['reship']) {
                    $this->cleanReturnStatus($sdf['reship']);
                }
                break;
            case '3':
                $data = array(
                    'status'    => $sdf['status'],
                    'return_id' => $returnProduct['return_id'],
                    'outer_lastmodify' => $sdf['modified'],
                    'choose_type_flag' => $sdf['choose_type_flag']
                );
                $modelReturnProduct->tosave($data, true);
                break;
            case '4':
                if ($sdf['reship'] && !$sdf['reship']['return_logi_name'] && !$sdf['reship']['return_logi_no']) {
                    $this->_updateReshipLogistics($sdf);
                }
                $operateLog->write_log('return@ome', $returnProduct['return_id'],'线上已完成,请进行收货/质检等操作');
                break;
            case '5':
                $data = array(
                    'status'    => $sdf['status'],
                    'return_id' => $returnProduct['return_id'],
                    'outer_lastmodify' => $sdf['modified'],
                );
                $modelReturnProduct->tosave($data, true);
                // 同步拒绝退货单
                if ($sdf['reship']){
                    $reship = $sdf['reship'];
                    app::get('ome')->model('reship')->update(array('is_check'=>'5','t_end'=>time()),array('reship_id'=>$reship['reship_id']));
                    $operateLog->write_log('reship@ome',$reship['reship_id'],'前端拒绝');
                }
                break;
            case '6':
                $this->_updateReshipLogistics($sdf);
                break;
            default:
                break;
        }
    }

    private function _updateReturnProductLogistics($returnId, $logisticsCompany, $logisticsNo) {
        if($returnId && $logisticsCompany && $logisticsNo) {
            $logisticsInfo = array(
                'shipcompany' => $logisticsCompany,
                'logino' => $logisticsNo,
            );
            $rData = array(
                'process_data' => serialize($logisticsInfo)
            );
            $rs = app::get('ome')->model('return_product')->update($rData, array('return_id' => $returnId));
            $memo = '更新物流公司:' . $logisticsCompany . ',物流单号:' . $logisticsNo;
            $operateLog = app::get('ome')->model('operation_log');
            $operateLog->write_log('return@ome', $returnId, $memo);
            return $rs;
        }
        return false;
    }

    private function _updateReshipLogistics($sdf){
        $reship = $sdf['reship'];
        $logisticsCompany = $sdf['logistics_company'];
        $logisticsNo = $sdf['logistics_no'];
        if ($reship && $logisticsCompany && $logisticsNo) {
            $memo ='更新物流公司:'.$logisticsCompany.',物流单号:'.$logisticsNo;
            $upData = array(
                'return_logi_name'=>$logisticsCompany,
                'return_logi_no'=>$logisticsNo,
                'outer_lastmodify'=>$sdf['modified'],
            );
            $rs = app::get('ome')->model('reship')->update($upData,array('reship_id'=>$reship['reship_id']));
            $operateLog = app::get('ome')->model('operation_log');
            $operateLog->write_log('reship@ome',$reship['reship_id'],$memo);
            $this->_updateReturnProductLogistics($reship['return_id'], $logisticsCompany, $logisticsNo);
            return $rs;
        }
        return false;
    }

    private function _dealReship($sdf) {

        $modelReship = app::get('ome')->model('reship');
        $operateLog = app::get('ome')->model('operation_log');
        if($sdf['reship']) {
            $msg = '仅处理未审核、拒绝状态和物流信息';
            if($sdf['reship']['shipcompany'] != $sdf['logistics_company'] || $sdf['reship']['logino'] != $sdf['logistics_no']) {
                if($this->_updateReshipLogistics($sdf)) {
                    $msg = '更新物流信息成功';
                }
            }
            if ($sdf['status'] == '5') {#拒绝
                if ($sdf['reship']['is_check']>0) {
                    return array('rsp'=>'fail', '本地退货单非未审核状态，不处理拒绝状态');
                }else{
                    $rs = $modelReship->update(array('is_check'=>'5'),array('reship_id'=>$sdf['reship']['reship_id'], 'is_check|noequal'=>'5'));
                    if(is_bool($rs)) {
                        $msg = '退货单已经被拒绝';
                    } else {
                        $msg = '退货单更新为拒绝状态';
                        $memo = '状态:拒绝';
                        $operateLog->write_log('reship@ome', $sdf['reship']['reship_id'], $memo);
                        if ($sdf['return_product']) {
                            $returnId = $sdf['return_product']['return_id'];
                            $rpData = array('status' => '5', 'last_modified' => time());
                            app::get('ome')->model('return_product')->update($rpData, array('return_id'=>$returnId));
                            $operateLog->write_log('return@ome', $returnId, $memo);
                        }
                    }
                }
            }
        } else {
            $insertData = $this->_reshipSdfToData($sdf);
            if($insertData['reship_items']) {
                $reshipItems = $insertData['reship_items'];
                unset($insertData['reship_items']);
            }
            $rs = $modelReship->insert($insertData);
            if(!$rs) {
                return array('rsp'=>'succ', 'msg'=>'退货单新建失败');
            }
            $operateLog->write_log('reship@ome',$insertData['reship_id'], '新建退货单');
            $this->_insertReshipItems($reshipItems, $insertData['reship_id']);
            if($sdf['return_product']['status'] < 3) {
                app::get('ome')->model('return_product')->update(array('status' => '3'), array('return_id' => $sdf['return_product']['return_id']));
                $operateLog->write_log('return@ome', $sdf['return_product']['return_id'], '由于退货单下载,售后单不为已接受更新为已接受');
            }
            $this->_updateReturnProductLogistics($sdf['return_product']['return_id'], $sdf['logistics_company'], $sdf['logistics_no']);
            //极速退款打标在扩展表
            if($sdf['jsrefund_flag'] == 'true'){
               
                $modelReship->db->exec("UPDATE sdb_ome_return_product_tmall set jsrefund_flag='true' WHERE return_bn='".$sdf['return_product']['return_bn']."'");
            }
            $msg = '新建退货单';
        }
        return array('rsp'=>'succ', 'msg'=>$msg);
    }

    private function _reshipSdfToData($sdf) {
        $tgOrder = $sdf['order'];
        $returnProduct = $sdf['return_product'];
        $opInfo = kernel::single('ome_func')->get_system();
        $data = array(
            'reship_bn'     => $sdf['refund_bn'],
            'shop_id'       => $sdf['shop_id'],
            'order_id'      => $tgOrder['order_id'],
            'delivery_id'   => $returnProduct['delivery_id'],
            'member_id'     => $tgOrder['member_id'],
            'logi_name'     => $sdf['logi_name'],
            'logi_no'       => $tgOrder['logi_no'],
            'logi_id'       => $tgOrder['logi_id'],
            'ship_name'     => $tgOrder['ship_name'],
            'ship_area'     => $tgOrder['ship_area'],
            'delivery'      => $tgOrder['shipping'],
            'ship_addr'     => $tgOrder['ship_addr'],
            'ship_zip'      => $tgOrder['ship_zip'],
            'ship_tel'      => $tgOrder['ship_tel'],
            'ship_email'    => $tgOrder['ship_email'],
            'ship_mobile'   => $tgOrder['ship_mobile'],
            'is_protect'    => $tgOrder['is_protect'],
            'return_id'     => $returnProduct['return_id'],
            'return_logi_name' => $sdf['logistics_company'],
            'return_logi_no' => $sdf['logistics_no'],
            'outer_lastmodify' => $sdf['modified'],
            'source'        => 'matrix',
            't_begin'       => $sdf['created'],
            'op_id'         => $opInfo['op_id'],
            'is_check'      => in_array($sdf['status'], array('0', '5')) ? $sdf['status'] : '0',
            'branch_id'     => $sdf['branch_id'],
        );
        if($sdf['refund_item_list']) {
            foreach ($sdf['refund_item_list'] as $item ) {
                $data['reship_items'][] = array(
                    'op_id'  => $opInfo['op_id'],
                    'bn'     => $item['bn'],
                    'num'    => $item['num'],
                    'price'  => $item['price'],
                    'branch_id' => $sdf['branch_id'],
                    'product_name' => $item['name'],
                    'product_id' => $item['product_id'],
                );

            }
            $data['tmoney'] = $returnProduct['money'];
            $data['totalmoney'] = $returnProduct['money'];//总计应退金额
        }
        return $data;
    }

    private function _insertReshipItems($reshipItems, $reshipId) {
        if(empty($reshipId) || empty($reshipItems)) {
            return false;
        }
        foreach($reshipItems as &$val) {
            $val['reship_id'] = $reshipId;
        }
        $modelItem = app::get('ome')->model('reship_items');
        $sql = ome_func::get_insert_sql($modelItem, $reshipItems);
        $rs = $modelItem->db->exec($sql);
        return $rs['rs'];
    }

    #清空本地状态和已生成单据
    private function cleanReturnStatus($reship){
        $return_id = (int) $reship['return_id'];
        $reship_id = (int) $reship['reship_id'];
        $oReship = app::get('ome')->model('reship');
        $oOperation_log = app::get('ome')->model('operation_log');//写日志
        $oReship->db->exec('DELETE FROM sdb_ome_reship WHERE reship_id='.$reship_id);
        $oReship->db->exec('DELETE FROM sdb_ome_reship_items WHERE reship_id='.$reship_id);
        $oReship->db->exec('DELETE FROM sdb_ome_return_process WHERE reship_id='.$reship_id);
        $oReship->db->exec('DELETE FROM sdb_ome_return_process_items WHERE reship_id='.$reship_id);
        $memo = '退款原因、金额或版本变化,已生成退货单' . $reship['reship_bn'] . '清除';
        $oOperation_log->write_log('return@ome',$return_id,$memo);
    }

    //识别是否天猫开启AG，如果开启的做标记接口请求
    private function _noticeAg($sdf){
        //取当前订单的处理状态
        $orderObj = app::get('ome')->model('orders');
        $order_filter = array("order_id"=>$sdf['order']['order_id']);
        $order_detail = $orderObj->dump($order_filter, 'order_bn,process_status,source');

        $aliag_status = app::get('ome')->getConf('shop.aliag.config.'.$sdf['shop_id']);
        if($aliag_status && $sdf['shop_type'] == 'tmall' && $sdf['status'] == 0 && $order_detail['source'] == 'matrix'){
            //识别是否开启AG并且是天猫订单的新建退款申请
            $params = array(
                'order_bn' => $order_detail['order_bn'],
                'apply_id' => $sdf['apply_id'],
                'refund_bn' => $sdf['refund_apply_bn'],
                'is_aftersale_refund' => false,
                'shop_id' => $sdf['shop_id'],
            );

            //检查当前订单的状态
            if(in_array($order_detail['process_status'],array('unconfirmed','confirmed'))){
                $params['cancel_dly_status'] = 'SUCCESS';
            }else{
                $params['cancel_dly_status'] = 'FAIL';
            }

            kernel::single('ome_service_refund')->refund_request($params);
        }
    }
}
